//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
#include <core.h>

#ifdef KCONFIG_MSTAT

// EXTERN
EXTERN Page *g_pPages;
EXTERN uint_t  g_uNumberOfPages;

static StatInfo s_statInfo;

#ifdef _x86

#define STAT_INFO_ALLOC(member, size) \
    do { \
        AtomicAdd((Int32 *)&member, (Int32)size); \
    } while (0)

#define STAT_INFO_FREE(member, size) \
    do { \
        AtomicSub((Int32 *)&member, (Int32)size); \
    } while (0)

#else

#define STAT_INFO_ALLOC(member, size)                               \
    do {                                                            \
        InterlockedExchangeAdd((Int32 *)&member, (Int32)size);       \
    } while (0)

#define STAT_INFO_FREE(member, size)                                \
    do {                                                            \
        InterlockedExchangeAdd((Int32 *)&member, -(Int32)size);      \
    } while (0)

#endif // _x86

EXTERN void GetStatInfo(StatInfo *pStatInfo)
{
    assert(pStatInfo);

    s_statInfo.uFreePages = GetNumberOfFreePages();
    s_statInfo.uTotalPages = g_uNumberOfActualPages;
    *pStatInfo = s_statInfo;
}

EXTERN Void StatInit()
{
    s_statInfo.uAllocedBytesOfCache = 0;
    s_statInfo.uTotalPagesOfCache = 0;
    s_statInfo.uAllocedKernelPages = 0;
    s_statInfo.uAllocedPhysicsPages = 0;
    s_statInfo.uTotalPages = 0;
    s_statInfo.uFreePages = 0;
}

EXTERN Void StatTotalPagesOfCache()
{
    InterlockedIncrement((Int32 *)&s_statInfo.uTotalPagesOfCache);
}

EXTERN Void StatKMalloc(UInt32 uBytes)
{
    STAT_INFO_ALLOC(s_statInfo.uAllocedBytesOfCache, uBytes);
}

EXTERN Void StatKFree(UInt32 uBytes)
{
    STAT_INFO_FREE(s_statInfo.uAllocedBytesOfCache, uBytes);
}

EXTERN Void StatAllocKernelPages(UInt32 uOrder)
{
    STAT_INFO_ALLOC(s_statInfo.uAllocedKernelPages, 1 << uOrder);
}

EXTERN Void StatFreeKernelPages(UInt32 uOrder)
{
    STAT_INFO_FREE(s_statInfo.uAllocedKernelPages, 1 << uOrder);
}

EXTERN Void StatAllocPages(UInt32 uOrder)
{
    STAT_INFO_ALLOC(s_statInfo.uAllocedPhysicsPages, 1 << uOrder);
}

EXTERN Void StatFreePages(UInt32 uOrder)
{
    STAT_INFO_FREE(s_statInfo.uAllocedPhysicsPages, 1 << uOrder);
}

#endif // KCONFIG_MSTAT
